/* RobotSystemPanel.js */

class RobotSystemPanel {
    static instance = null;

    static initialize() {
        if (RobotSystemPanel.instance) {
            console.warn('RobotSystemPanel already initialized');
            return RobotSystemPanel.instance;
        }

        const maxAttempts = 10;
        let attempts = 0;

        const tryInitialize = () => {
            return new Promise((resolve, reject) => {
                const attempt = () => {
                    attempts++;
                    const container = document.getElementById('system-info');

                    if (container) {
                        try {
                            RobotSystemPanel.instance = new RobotSystemPanel(container);
                            console.log('System info panel initialized');
                            resolve(RobotSystemPanel.instance);
                        } catch (error) {
                            reject(error);
                        }
                    } else if (attempts < maxAttempts) {
                        setTimeout(attempt, 100);
                    } else {
                        reject(new Error('System info panel container not found'));
                    }
                };

                attempt();
            });
        };

        return tryInitialize();
    }

    constructor(container) {
        if (RobotSystemPanel.instance) {
            return RobotSystemPanel.instance;
        }

        this.container = container;
        this.stateManager = window.robotStateManager;

        this.state = {
            cpu: {
                usage: 0,
                temperature: 0
            },
            memory: {
                total: 0,
                used: 0,
                free: 0
            },
            disk: {
                total: 0,
                used: 0,
                free: 0
            },
            network: {
                rx: 0,
                tx: 0
            },
            versions: {
                system: "1.0.0",
                firmware: "2.0.0",
                hardware: "A1.0"
            }
    };

        this.init();
    }

    renderUI() {
        this.container.innerHTML = `
            <div class="system-panel">
                <div class="module-title">系统信息</div>

                <!-- 版本信息 -->
                <div class="info-row">
                    <div class="info-item">
                        <label class="info-label">
                            <i data-lucide="box"></i>
                            <span>固件版本</span>
                        </label>
                        <div class="info-value">v2.0.0</div>
                    </div>
                    <div class="info-item">
                        <label class="info-label">
                            <i data-lucide="cpu"></i>
                            <span>硬件版本</span>
                        </label>
                        <div class="info-value">A1.0</div>
                    </div>
                </div>

                <!-- CPU & 温度 -->
                <div class="info-row">
                    <div class="info-item">
                        <label class="info-label">
                            <i data-lucide="cpu"></i>
                            <span>CPU</span>
                        </label>
                        <div class="info-value">0%</div>
                    </div>
                    <div class="info-item">
                        <label class="info-label">
                            <i data-lucide="thermometer"></i>
                            <span>温度</span>
                        </label>
                        <div class="info-value">0°C</div>
                    </div>
                </div>

                <!-- 内存 & 磁盘 -->
                <div class="info-row">
                    <div class="info-item">
                        <label class="info-label">
                            <i data-lucide="database"></i>
                            <span>内存</span>
                        </label>
                        <div class="info-value">0 MB</div>
                    </div>
                    <div class="info-item">
                        <label class="info-label">
                            <i data-lucide="hard-drive"></i>
                            <span>磁盘</span>
                        </label>
                        <div class="info-value">0 GB</div>
                    </div>
                </div>

                <!-- 网络状态 -->
                <div class="info-row">
                    <div class="info-item">
                        <label class="info-label">
                            <i data-lucide="arrow-down"></i>
                            <span>接收</span>
                        </label>
                        <div class="info-value">0 KB/s</div>
                    </div>
                    <div class="info-item">
                        <label class="info-label">
                            <i data-lucide="arrow-up"></i>
                            <span>发送</span>
                        </label>
                        <div class="info-value">0 KB/s</div>
                    </div>
                </div>
            </div>
        `;

        // 初始化图标
        lucide.createIcons();
    }

    bindEvents() {
        // 绑定事件监听器（如果需要）
    }

    subscribeToStateChanges() {
        this.stateManager.addListener(state => {
            this.updateUI(state);
        });
    }

    updateUI(state) {
        if (!state?.system) return;

        const { cpu, memory, disk, network, versions } = state.system;

        // 更新版本信息
        if (versions) {
            this.container.querySelector('.info-row:first-child .info-item:first-child .info-value')
                .textContent = `v${versions.firmware}`;
            this.container.querySelector('.info-row:first-child .info-item:last-child .info-value')
                .textContent = versions.hardware;
        }

        // 更新CPU信息
        if (cpu) {
            this.container.querySelector('.system-item:nth-child(1) .value').textContent =
                cpu.usage.toFixed(1);
            this.container.querySelector('.system-item:nth-child(2) .value').textContent =
                cpu.temperature.toFixed(1);
        }

        // 更新内存信息
        if (memory) {
            const usedMemory = (memory.used / 1024).toFixed(1);
            this.container.querySelector('.system-item:nth-child(3) .value').textContent = usedMemory;
        }

        // 更新磁盘信息
        if (disk) {
            const usedDisk = (disk.used / 1024 / 1024).toFixed(1);
            this.container.querySelector('.system-item:nth-child(4) .value').textContent = usedDisk;
        }

        // 更新网络状态
        if (network) {
            const formatSpeed = (speed) => {
                if (speed < 1024) return `${speed.toFixed(1)} KB/s`;
                return `${(speed / 1024).toFixed(1)} MB/s`;
            };

            this.container.querySelector('.network-item:nth-child(1) .network-value').textContent =
                formatSpeed(network.rx);
            this.container.querySelector('.network-item:nth-child(2) .network-value').textContent =
                formatSpeed(network.tx);
        }
    }

    init() {
        this.renderUI();
        this.bindEvents();
        this.subscribeToStateChanges();
    }

    destroy() {
        if (this.stateManager) {
            this.stateManager.removeListener(this.updateUI.bind(this));
        }
        if (this.container) {
            this.container.innerHTML = '';
        }
    }
}

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.RobotSystemPanel = RobotSystemPanel;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        RobotSystemPanel
    };
}